<template>
  <el-cascader
    :options="options"
    placeholder="车型"
    @active-item-change="getNodes"
    @change="cascaderChange"
    :props="prop"
    filterable></el-cascader>
</template>

<script>

  import { carModelList, vehicleList, brandList } from '@/api/after-sale/carModel'
  export default {
    name: 'CarModelFrom',
    props: {
      checkStrictly: { type: Boolean, default: false }
    },
    data() {
      return {
        brandList: [],
        vehicleList: [],
        carModelList: [],
        options: [],
        prop: {
          value: 'id',
          label: 'name',
          children: 'children',
          checkStrictly: this.checkStrictly
        }
      }
    },
    created() {
      this.getBrandList()
    },
    methods: {
      cascaderChange(val) {
        this.$emit('operate', val)
      },
      getNodes(val) {
        if (val.length === 1) {
          this.getVehicleList(val[0])
        } else if (val.length === 2) {
          this.getCarModelList(val[0], val[1])
        }
      },
      async getBrandList() {
        const { data } = await brandList()
        this.brandList = data
        data.map(item => {
          this.$set(item, 'id', item.id)
          this.$set(item, 'name', item.value)
          this.$set(item, 'children', [])
        })
        this.options = data
      },
      async getVehicleList(brandId) {
        const { data } = await vehicleList(brandId)
        this.vehicleList = data
        data.map(item => {
          this.$set(item, 'id', item.id)
          this.$set(item, 'name', item.value)
          this.$set(item, 'children', [])
        })
        this.options.map((item, i) => {
          if (item.id === brandId) {
            item.children = data
            return
          }
        })
      },
      async getCarModelList(brandId, vehicleId) {
        const { data } = await carModelList(vehicleId)
        this.carModelList = data
        data.map(item => {
          this.$set(item, 'id', item.id)
          this.$set(item, 'name', item.value)
        })
        this.options.map((item, i) => {
          if (item.id === brandId) {
            item.children.map((city, idx) => {
              if (city.id === vehicleId) {
                city.children = data
              }
              return
            })
            return
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
